package com.yk.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yk.api.system.dto.MessageDTO;
import com.yk.common.core.constant.NumberConstant;
import com.yk.common.core.exception.ServiceException;
import com.yk.system.entity.Device;
import com.yk.system.entity.Message;
import com.yk.system.mapper.MessageMapper;
import com.yk.system.service.MessageService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 消息 服务类
 *
 * @author lmx
 * @since 2023-12-16
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Override
    public int updateBatch(List<Message> list) {
        return baseMapper.updateBatch(list);
    }

    @Override
    public int batchInsert(List<Message> list) {
        return baseMapper.batchInsert(list);
    }

    @Override
    public void systemMessage(String title, Long userId, String content, String type) {
        Message message = new Message();
        message.setTitle(title);
        message.setUserId(userId);
        message.setContent(content);
        message.setType(type);
        baseMapper.insert(message);
    }

    @Override
    public void shareMessage(String content, Long shareId, Long sharedId, Long deviceRoleId, Boolean receiveStatus, Long targetId) {
        Message message = new Message();
        message.setTitle("设备共享消息");
        message.setUserId(shareId);
        message.setContent(content);
        message.setShareId(shareId);
        message.setSharedId(sharedId);
        message.setDeviceRoleId(deviceRoleId);
        message.setType(NumberConstant.ONE_STR);
        message.setTargetType(NumberConstant.ONE_STR);
        message.setTargetId(targetId);
        message.setReceiveStatus(receiveStatus);
        baseMapper.insert(message);
        updateReceiveStatusByDeviceRoleId(deviceRoleId, receiveStatus);
    }

    @Override
    public void configurationShareMessage(String content, Long shareId, Long sharedId, Long deviceRoleId, Boolean receiveStatus, Long targetId) {
        Message message = new Message();
        message.setTitle("组态共享消息");
        message.setUserId(shareId);
        message.setContent(content);
        message.setShareId(shareId);
        message.setSharedId(sharedId);
        message.setDeviceRoleId(deviceRoleId);
        message.setType(NumberConstant.ONE_STR);
        message.setTargetType(NumberConstant.TWO_STR);
        message.setTargetId(targetId);
        message.setReceiveStatus(receiveStatus);
        baseMapper.insert(message);
        updateReceiveStatusByDeviceRoleId(deviceRoleId, receiveStatus);
    }

    @Override
    public void sharedMessage(String content, Long shareId, Long sharedId, Long deviceRoleId,
                              Boolean receiveStatus, Long targetId) {
        Message message = new Message();
        message.setTitle("设备共享消息");
        message.setUserId(sharedId);
        message.setContent(content);
        message.setShareId(shareId);
        message.setSharedId(sharedId);
        message.setDeviceRoleId(deviceRoleId);
        message.setType(NumberConstant.ONE_STR);
        message.setTargetType(NumberConstant.ONE_STR);
        message.setTargetId(targetId);
        message.setReceiveStatus(receiveStatus);
        baseMapper.insert(message);
        updateReceiveStatusByDeviceRoleId(deviceRoleId, receiveStatus);
    }

    @Override
    public void configurationSharedMessage(String content, Long shareId, Long sharedId, Long deviceRoleId,
                                           Boolean receiveStatus, Long targetId) {
        Message message = new Message();
        message.setTitle("组态共享消息");
        message.setUserId(sharedId);
        message.setContent(content);
        message.setShareId(shareId);
        message.setSharedId(sharedId);
        message.setDeviceRoleId(deviceRoleId);
        message.setType(NumberConstant.ONE_STR);
        message.setTargetType(NumberConstant.TWO_STR);
        message.setTargetId(targetId);
        message.setReceiveStatus(receiveStatus);
        baseMapper.insert(message);
        updateReceiveStatusByDeviceRoleId(deviceRoleId, receiveStatus);
    }

    @Override
    public List<Message> pageByTime(MessageDTO param) {
        return baseMapper.pageByTime(param);
    }

    @Override
    public Integer countPageByTime(MessageDTO param) {
        return baseMapper.countPageByTime(param);
    }

    @Override
    public void updateReceiveStatus(Long deviceRoleId) {
        if (Objects.isNull(deviceRoleId)) {
            return;
        }
        LambdaQueryWrapper<Message> lambda = new LambdaQueryWrapper<>();
        lambda.eq(Message::getDeviceRoleId, deviceRoleId);
        List<Message> messages = baseMapper.selectList(lambda);
        if (CollUtil.isNotEmpty(messages)) {
            messages.forEach(message -> {
                message.setReceiveStatus(Boolean.TRUE);
                baseMapper.updateById(message);
            });
        }
    }

    @Override
    public void checkShare(Long sharedId, Long shareId, String targetType, Long targetId) {
        LambdaQueryWrapper<Message> lambda = new LambdaQueryWrapper<>();
        lambda.eq(Message::getSharedId, sharedId);
        lambda.eq(Message::getShareId, shareId);
        lambda.eq(Message::getTargetType, targetType);
        lambda.eq(Message::getTargetId, targetId);
        lambda.isNull(Message::getReceiveStatus);
        Long count = baseMapper.selectCount(lambda);
        if (count > 0) {
            throw new ServiceException("已向对方发送共享消息，请勿再次发送");
        }
    }

    @Override
    public void batchCheckShare(Device device, Long sharedId, Long shareId, String targetType) {
        LambdaQueryWrapper<Message> lambda = new LambdaQueryWrapper<>();
        lambda.eq(Message::getSharedId, sharedId);
        lambda.eq(Message::getShareId, shareId);
        lambda.eq(Message::getTargetType, targetType);
        lambda.eq(Message::getTargetId, device.getId());
        lambda.isNull(Message::getReceiveStatus);
        Long count = baseMapper.selectCount(lambda);
        if (count > 0) {
            throw new ServiceException("已向对方发送设备["+ device.getDeviceName() +"]共享消息，请勿再次发送");
        }
    }

    /**
     * 根据设备id更新接收状态
     */
    private void updateReceiveStatusByDeviceRoleId(Long deviceRoleId, Boolean receiveStatus) {
        if (Objects.isNull(deviceRoleId) || Objects.isNull(receiveStatus)) {
            return;
        }
        LambdaQueryWrapper<Message> lambda = new LambdaQueryWrapper<>();
        lambda.eq(Message::getDeviceRoleId, deviceRoleId).isNull(Message::getReceiveStatus);
        List<Message> messages = baseMapper.selectList(lambda);
        if (CollUtil.isNotEmpty(messages)) {
            messages.forEach(message -> {
                message.setReceiveStatus(receiveStatus);
                baseMapper.updateById(message);
            });
        }
    }
}